package com.miras.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import sun.misc.BASE64Encoder;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

import static com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode;

/**
 * @author Gjing
 *
 * netty服务端处理器
 **/
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    private Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Channel active......");
    }

    /**
     * 客户端发消息会触发
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String strUTF8 = "";
        String puhuo = "" ;
        String puhuoNew = "";
        if (msg.toString().contains("{\"")){
            strUTF8 = "["+URLDecoder.decode(msg.toString(), "UTF-8")+"]";
            puhuo = strUTF8.replace("*","");
           // puhuoNew = puhuo.replace("}{","},\\r{");
        }
        //puhuo = URLDecoder.decode(msg.toString(), "UTF-8");
        //log.info("服务器收到消息：{}",puhuo);
        //ctx.write("你也好哦");
        if (puhuo!="" || puhuo != null){
           KafKaProducer.inBoundKafka ("puhuo","puhuokey",puhuo);
        }
        //ctx.flush();
    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
